import Vue from "vue";
import { Notification } from 'element-ui';

const vueIns = new Vue()

export default function(app) {
  const axios = app.$axios;
  // 添加请求拦截
  /* eslint-disable camelcase */
  axios.interceptors.request.use(
    config => {
      const {
        user: { token }
      } = app.store.state;
      console.log('token-->', token);
      if (token) {
        config.headers = {
          Authorization: token
        };
      }
      return config;
    },
    error => {
      catchError(error);
      return Promise.reject(error);
    }
  );

  // 添加返回拦截
  axios.interceptors.response.use(
    res => {
      const { code, msg} = res.data
      if (code === 1) {
        return res
      }
      console.log('code', code);
      if (code === 2004 || code === 2001) {
        loginOut()
      }
      return catchError({code, msg}, res)
    },
    error => {
      const { response: {status, data}, message } = error
      return typeof data === "object" ?
             catchError(data, error) :
             catchError({code: status, msg: message}, error)
    }
  );
  
  /**
   *
   * @param {Error} err http报错信息
   */
  function catchError(info, err) {
    const { code, msg } = info;

    Notification.warning({
      title: "错误",
      message: `错误信息：${code}, ${msg}`
    });
    return Promise.reject(err)
  }
  
  function loginOut() {
    console.log('推出登录', app);
    app.store.commit('user/set', {user: {}, token: ''})
    app.app.router.push('/login')
  }
  
  Vue.post = Vue.prototype.$post = function(
    url,
    params = {},
    { convert = false, config = {} } = {}
  ) {
    return axios(
      Object.assign(
        {
          method: "post",
          url,
          data: convert ? Vue.paramsConvert(params) : params
        },
        config
      )
    );
  };

  Vue.post = Vue.prototype.$put = function(
    url,
    params = {},
    { convert = false, config = {} } = {}
  ) {
    return axios(
      Object.assign(
        {
          method: "put",
          url,
          data: convert ? Vue.paramsConvert(params) : params
        },
        config
      )
    );
  };

  /**
   * get请求
   *
   * @param {String} url 请求路径
   * @param {Object} params 请求参数
   * @param {Object} Object 一些额外的配置参数
   *
   * @return {Promise} 返回Promise对象
   */
  Vue.get = Vue.prototype.$get = function(
    url,
    params = {},
    { config = {} } = {}
  ) {
    return axios(
      Object.assign(
        {
          method: "get",
          url,
          params
        },
        config
      )
    );
  };

  /**
   * delete请求
   *
   * @param {String} url 请求路径
   * @param {Object} params 请求参数
   * @param {Object} Object 一些额外的配置参数
   *
   * @return {Promise} 返回Promise对象
   */
  Vue.delete = Vue.prototype.$delete = function(
    url,
    params = {},
    { config = {} } = {}
  ) {
    return axios(
      Object.assign(
        {
          method: "delete",
          url,
          params
        },
        config
      )
    );
  };
}
